package dy.app.util;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;

import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 转换相关工具类
 * Author: cKnight
 * Date: 2024/6/11
 */
@Slf4j
public class ConvUtils {


    /**
     * pageMap转化 需要DO 转 VO
     *
     * @param page
     * @param toClass
     * @return
     */
    public static <I, O> Map<String, Object> toPageResult(Page<I> page, Class<O> toClass) {
        Map<String, Object> results = new HashMap<>(3);
        results.put("total_record", page.getTotal());
        results.put("total_page", page.getPages());
        if (Objects.isNull(toClass)) {
            results.put("current_data", page.getRecords());
        } else {
            results.put("current_data", listFromTo(page.getRecords(), toClass));
        }
        return results;
    }

    /**
     * 单个对象转换
     *
     * @param from
     * @param clazz
     * @param <I>
     * @param <O>
     * @return
     */
    public static <I, O> O beanProcess(I from, Class<O> clazz) {
        try {
            O t = clazz.getDeclaredConstructor().newInstance();
            BeanUtils.copyProperties(from, t);
            return t;
        } catch (InstantiationException | IllegalAccessException | InvocationTargetException |
                 NoSuchMethodException e) {
            log.error("反射获取对象失败:{}", clazz.getSimpleName());
            log.error("反射获取对象异常", e);
            return null;
        }
    }


    /**
     * list DO 转 VO
     *
     * @param list
     * @param clazz
     * @return
     */
    public static <I, O> List<O> listFromTo(List<I> list, Class<O> clazz) {
        return list.stream().map(obj -> beanProcess(obj, clazz)).collect(Collectors.toList());
    }
}
